

from datetime import datetime
from sqlalchemy.orm import relationships, Mapped, mapped_column
from db.db_base import BaseModel
from sqlalchemy import String, Boolean, DateTime
from passlib.context import CryptContext
from .role import Role
from .m2m import user_roles

pwd_context = CryptContext(schemes=["bcrytp"], deprecated="auto")


class User(BaseModel):
    __tablename__ = "user"
    __table_args__ = ({"comment": "用户表"})

    name: Mapped[str] = mapped_column(String(50), index=True, nullable=False, comment="姓名")
    nickname: Mapped[str | None] = mapped_column(String(50), nullable=True, comment="昵称")
    telephone: Mapped[str] = mapped_column(String(11), nullable=False, index=True, comment="手机号", unique=False)
    email: Mapped[str | None] = mapped_column(String(50), comment="邮箱地址")
    password: Mapped[str] = mapped_column(String(255), nullable=True, comment="密码")
    gender: Mapped[str | None] = mapped_column(String(8), nullable=True, comment="性别")
    isvalid: Mapped[bool] = mapped_column(Boolean, default=True, comment="是否可用")
    is_reset_password: Mapped[bool] = mapped_column(Boolean, default=False, comment="首次登陆重置密码")
    roles: Mapped[set[Role]] = relationships(secondary=user_roles)

    @staticmethod
    def get_password_hash(password: str) -> str:
        """ 生成 密码 hash """
        return pwd_context.hash(password)
    
    @staticmethod
    def verify_password(password: str, hashed_password: str) -> bool:
        """ 对比hash后的密码 和 已经加满后的密码是否相等 """
        return pwd_context.verify(password, hashed_password)
    
    def is_admin(self) -> bool:
        """ 判断是否有最高权限 """
        return any([i.is_admin for i in self.roles])

